/**
 * @author LKQ
 * @date 2021/11/30 22:16
 * @description 采用二分查找，使时间复杂度降为O(logN)
 */
public class HalveSolution {
    public static void main(String[] args) {
        HalveSolution solution = new HalveSolution();
        int[] nums = {1, 3, 5, 6};
        System.out.println(solution.searchInsert(nums, 2));
    }
    public int searchInsert(int[] nums, int target) {
        int n = nums.length;
        int left = 0, right = n- 1, ans = n;
        while (left<= right) {
            // 不要使用(left+right)/ 2, 会计算溢出。
            int mid = left + (right - left) / 2;
            if (target<=nums[mid]) {
                right = mid - 1;
                ans = mid;
            }else {
                left = mid + 1;
            }
        }
        return ans;
    }

}
